package com.uhylab.uhuvinetest.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.uhylab.uhuvinetest.R;
import com.uhylab.uhuvinetest.adapter.BleSevicesListAdapter;
import com.uhylab.uhuvinetest.service.BleService;
import com.uhylab.uhuvinetest.utils.Utils;
import com.uhylab.uhuvinetest.utils.toastutil.ToastUtil;
import com.uhylab.uhuvinetest.view.VelocimeterView;
import com.zhy.autolayout.AutoLinearLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;



public class UHDeviceControlActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
    public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";

    public static final String FIND_DEVICE_ALARM_ON = "find.device.alarm.on";
    public static final String DISCONNECT_DEVICE = "find.device.disconnect";
    public static final String CANCEL_DEVICE_ALARM = "find.device.cancel.alarm";
    public static final String DEVICE_BATTERY = "device.battery.level";

    private String ser_uuid = "0000ffa0-0000-1000-8000-00805f9b34fb";

    private String wirte_uuid = "0000ffa3-0000-1000-8000-00805f9b34fb";
    private String read_uuid = "0000ffa2-0000-1000-8000-00805f9b34fb";


    private TextView textview;
    private Button send;
    private Button read;

    private VelocimeterView mVelocimeterView;
    private ImageView iv_back;
    private TextView tv_jump;
    private Button next;

    private VideoView vv_u2;
    private ImageView main_more;

    private AutoLinearLayout frame1;
    private LinearLayout frame2;
    private AutoLinearLayout frame0;

    BluetoothGattCharacteristic gatt_write;
    BluetoothGattCharacteristic gatt_read;

    ListView serviceList;
    SwipeRefreshLayout swagLayout;
    BleSevicesListAdapter servicesListAdapter;

    Intent intent;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    public static String bleAddress;
    List<BluetoothGattService> gattServices = new ArrayList<BluetoothGattService>();
    List<BluetoothGattService> copygattServices = new ArrayList<BluetoothGattService>();
    BleService bleService;
    int rssi;
    private String result;

    private boolean isU2 = false;

    private boolean requirs = false ;

    //传入下一步的四种H值
    private float[] HFloats = new float[4];

      private Handler handler = new Handler() {
              @Override
              public void handleMessage(Message msg) {
                  super.handleMessage(msg);
                  switch (msg.what) {
                      case 0:
                          vv_u2.start();
                          break;
                      case 1:
                          float value = mVelocimeterView.getValue();
                          value += 1;
                          handler.sendEmptyMessageDelayed(1,1000);
                          if (value > mVelocimeterView.getMax()) {
                              value = mVelocimeterView.getMax();
                              handler.removeMessages(1);
//                              ToastUtil.show(UHDeviceControlActivity.this,"动画结束");
                              if (result != null && requirs == true) {
                                  enterNextActivity();
                              } else {
                                  handler.sendEmptyMessageDelayed(1,1000);
                              }
                              Log.e("TAG",result + "结果");
                              Log.e("TAG",requirs + "判断");
                          }
                          mVelocimeterView.setValue(value);
                          Log.e("TAG",value + "每隔1s");
                          if (value == 30) {
                              writeDialog();
                              Log.e("TAG","这个时间段写OK么");
                          }
                          if (value == 40) {
                              bleService.mBluetoothGatt.readCharacteristic(gatt_read);
                          }
                          break;
                      case 2:

                          enterNextActivity();

                          break;
                  }
              }
          };

    private final ServiceConnection conn = new ServiceConnection() {
        @SuppressLint("NewApi")
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // TODO Auto-generated method stub
            bleService = ((BleService.LocalBinder) service).getService();
            if (!bleService.init()) {
                finish();
            }
            bleService.connect(bleAddress);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
            bleService = null;
        }
    };

    BroadcastReceiver mbtBroadcastReceiver = new BroadcastReceiver() {

        @SuppressLint({ "NewApi", "DefaultLocale" })
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if (BleService.ACTION_GATT_CONNECTED.equals(action)) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(UHDeviceControlActivity.this, "设备连接成功！",
                                Toast.LENGTH_LONG).show();
                    }
                });
            }
            if (BleService.ACTION_GATT_DISCONNECTED.equals(action)) {
                Toast.makeText(UHDeviceControlActivity.this, "设备断开！", Toast.LENGTH_LONG)
                        .show();
                if (sharedPreferences.getBoolean("AutoConnect", true)) {
                    bleService.connect(bleAddress);
                }
            }
            if (BleService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                String uuid = null;
                bleService.mBluetoothGatt.readRemoteRssi();
                gattServices = bleService.mBluetoothGatt.getServices();
                copygattServices = bleService.mBluetoothGatt.getServices();
                final ArrayList<HashMap<String, String>> serviceNames = new ArrayList<HashMap<String, String>>();
                for (BluetoothGattService ser : gattServices) {

                    HashMap<String, String> currentServiceData = new HashMap<String, String>();
                    uuid = ser.getUuid().toString();
                    currentServiceData.put("Name", Utils.attributes
                            .containsKey(uuid) ? Utils.attributes.get(uuid)
                            : "Unknown Service");
                    serviceNames.add(currentServiceData);

                    if (ser.getUuid().toString().equals("0000ffa0-0000-1000-8000-00805f9b34fb")) {

                        //标志在该设备中找到该服务,如果一直没有找到,说明该设备不是我们要找的设备
                        isU2 = true ;

                        final List<BluetoothGattCharacteristic> gattchars = ser
                                .getCharacteristics();
                        for (BluetoothGattCharacteristic c : gattchars) {

                            String uuidStr = c.getUuid().toString();
                            Log.e("TAG", uuidStr);
                            if (c.getUuid().toString().equals(wirte_uuid)) {
                                gatt_write = bleService.mBluetoothGatt.getService(ser.getUuid())
                                        .getCharacteristic(UUID.fromString(wirte_uuid));
                                Log.e("TAG","得到ffa3");
                            }
                            if (c.getUuid().toString().equals(read_uuid)){
                                gatt_read = bleService.mBluetoothGatt.getService(ser.getUuid())
                                        .getCharacteristic(UUID.fromString(read_uuid));
                                Log.e("TAG","得到ffa2");
                            }
                            if (gatt_write == null | gatt_read == null) {
                                Log.e("TAG", "其值为空");
                            }
                        }

                    }
                }

               // ToastUtil.show(UHDeviceControlActivity.this,"读取数据成功");
                runOnUiThread(new Runnable() {
                    @SuppressLint("NewApi")
                    public void run() {

                        if (isU2 == false) {
                            new AlertDialog.Builder(UHDeviceControlActivity.this)
                                    .setMessage("您选择的该设备不是U2设备,请重新选择")
                                    .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            UHDeviceControlActivity.this.finish();
                                        }
                                    }).show();
                        } else {
                            frame0.setVisibility(View.GONE);
                            frame2.setVisibility(View.VISIBLE);
                        }

                    }
                });

            }
            if (BleService.ACTION_GATT_RSSI.equals(action)) {
                rssi = intent.getExtras().getInt(BleService.EXTRA_DATA_RSSI);
                UHDeviceControlActivity.this.invalidateOptionsMenu();
            }

            if (BleService.ACTION_CHAR_READED.equals(action)) {
                final String hexValue = intent.getExtras()
                        .getString("HexValue");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated methdo stub
                        textview.setText("十六进制: " + hexValue);
                        result = hexValue;
                        requirs = true;
                        Log.e("TAG",result + "得到");
                        Log.e("TAG",requirs + "panduan");
                    }
                });
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_uhdevice_control);
        //getActionBar().setTitle("服务列表");
        sharedPreferences = getPreferences(0);
        editor = sharedPreferences.edit();

        init();
        bindBleSevice();
        registerReceiver(mbtBroadcastReceiver, makeGattUpdateIntentFilter());
    }

    private void bindBleSevice() {
        Intent serviceIntent = new Intent(this, BleService.class);
        bindService(serviceIntent, conn, BIND_AUTO_CREATE);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void init() {
        serviceList = (ListView) findViewById(R.id.lv_deviceList);
        serviceList.setEmptyView(findViewById(R.id.pb_empty));
        servicesListAdapter = new BleSevicesListAdapter(this);
        swagLayout = (SwipeRefreshLayout) findViewById(R.id.swagLayout);
        swagLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @SuppressLint("NewApi")
            @Override
            public void onRefresh() {
                // TODO Auto-generated method stub
                servicesListAdapter.clear();
                bleService.mBluetoothGatt.discoverServices();
                servicesListAdapter.notifyDataSetChanged();
                swagLayout.setRefreshing(false);
            }
        });
        serviceList.setAdapter(servicesListAdapter);
        bleAddress = getIntent().getExtras().getString((EXTRAS_DEVICE_ADDRESS));
        Log.e("TAG",bleAddress);

        textview = (TextView) findViewById(R.id.textview);
        send = (Button) findViewById(R.id.send);
        read = (Button) findViewById(R.id.read);
        vv_u2 = (VideoView) findViewById(R.id.vv_u2);
        frame0 = (AutoLinearLayout) findViewById(R.id.frame0);
        frame1 = (AutoLinearLayout) findViewById(R.id.frame1);
        frame2 = (LinearLayout) findViewById(R.id.frame2);
        main_more = (ImageView) findViewById(R.id.main_more);

        mVelocimeterView = (VelocimeterView) findViewById(R.id.velocimeter);
        iv_back = (ImageView) findViewById(R.id.iv_back);
        tv_jump = (TextView) findViewById(R.id.tv_jump);
        next = (Button) findViewById(R.id.next);

        send.setOnClickListener(this);
        read.setOnClickListener(this);
        frame1.setVisibility(View.GONE);
        frame2.setVisibility(View.GONE);

        mVelocimeterView.setValue(0);
        iv_back.setOnClickListener(this);
        tv_jump.setOnClickListener(this);
        main_more.setOnClickListener(this);
        next.setOnClickListener(this);

        setVideo();
    }

    private void setVideo() {
        String uri = "android.resource://" + getPackageName() + "/" + R.raw.u2;
        vv_u2.setVideoURI(Uri.parse(uri));
        vv_u2.start();
        vv_u2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                handler.sendEmptyMessageDelayed(0,5000);
            }
        });
    }

    public void showDialog() {
        new AlertDialog.Builder(this)
                .setMessage("您看清楚了么？")
                .setPositiveButton("再来一遍", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        vv_u2.start();
                    }
                })
                .setNegativeButton("结束", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //finish();
                    }
                }).show();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        bleService.close(bleService.mBluetoothGatt);
        unbindService(conn);
        unregisterReceiver(mbtBroadcastReceiver);
        handler.removeCallbacksAndMessages(null);
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BleService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BleService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BleService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BleService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(BleService.BATTERY_LEVEL_AVAILABLE);
        intentFilter.addAction(BleService.ACTION_GATT_RSSI);
        intentFilter.addAction(BleService.ACTION_CHAR_READED);

        return intentFilter;
    }

    @SuppressLint("NewApi")
    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        // TODO Auto-generated method stub
        getMenuInflater().inflate(R.menu.services, menu);
        menu.getItem(1).setTitle(rssi + "");
        menu.getItem(0).setVisible(false);
        return true;
    }

    @SuppressLint("NewApi")
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        if (item.getItemId() == R.id.menu_rssi)
            item.setTitle(rssi + "");
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send :
                writeDialog();
                break;
            case R.id.read :
                bleService.mBluetoothGatt.readCharacteristic(gatt_read);
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_jump:
                ToastUtil.show(this,"点击跳过");
                bleService.mBluetoothGatt.readCharacteristic(gatt_read);
                enterNextActivity();
                break;
            case R.id.main_more :
                finish();
                break;
            case R.id.next :
                writeDialog();
                frame1.setVisibility(View.VISIBLE);
                frame2.setVisibility(View.GONE);
                handler.removeMessages(0);
                handler.sendEmptyMessage(1);
                break;

        }
    }

    private void writeDialog() {
        String charvalue = "1000";

        byte[] str = str2Byte(charvalue);
        gatt_write.setValue(str);

        bleService.mBluetoothGatt.writeCharacteristic(gatt_write);
    }

    public static byte[] str2Byte(String hexStr) {
        int b = hexStr.length() % 2;
        if (b != 0) {
            hexStr = "0" + hexStr;
        }
        String[] a = new String[hexStr.length() / 2];
        byte[] bytes = new byte[hexStr.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            a[i] = hexStr.substring(2 * i, 2 * i + 2);
        }
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(a[i], 16);
        }
        return bytes;
    }


    //带着数据优雅的进入展示页面
    private void enterNextActivity() {
        Intent intent = new Intent(this,UHU2ResultActivity.class);
        //intent.putExtra("string",result);
        if (result == null || requirs == false) {
            handler.sendEmptyMessageDelayed(2,2000);
        } else {
            setH4();
            intent.putExtra("floats",HFloats);
            startActivity(intent);
            Log.e("TAG",requirs + "requires的值");
            finish();
        }
    }

    //得到result值之后,分别获取四个色块的H值
    private void setH4() {
        float h0 = GRB2H(Integer.parseInt(result.substring(0,2),16),Integer.parseInt(result.substring(2,4),16),Integer.parseInt(result.substring(4,6),16));
        float h1 = GRB2H(Integer.parseInt(result.substring(6,8),16),Integer.parseInt(result.substring(8,10),16),Integer.parseInt(result.substring(10,12),16));
        float h2 = GRB2H(Integer.parseInt(result.substring(12,14),16),Integer.parseInt(result.substring(14,16),16),Integer.parseInt(result.substring(16,18),16));
        float h3 = GRB2H(Integer.parseInt(result.substring(18,20),16),Integer.parseInt(result.substring(20,22),16),Integer.parseInt(result.substring(22),16));

        Log.e("TAG",h0 + "  " + h1 + "  " + h2 + "   " + h3 + "  ");

        if ((h0 > 180) && (h0 < 280)) {
            HFloats[0] = h0 + 180;
        } else if (h0 < 180) {
            HFloats[0] = h0 + 360;
        } else if (h0 >= 280) {
            HFloats[0] = h0;
        }


        if ((h1 > 180) && (h1 < 240)) {
            HFloats[1] = h1 + 180;
        } else if (h1 < 180) {
            HFloats[1] = h1 + 360;
        } else if (h1 >= 240) {
            HFloats[1] = h1;
        }

        HFloats[2] = h2 > 180 ? h2 : h2 + 360;
//                        HFloat3 = H[3] > 180 ? H[3] : H[3] + 360;
        HFloats[3] = h3;
    }

    //将RGB值转换成HSV,此处只取H值
    public float GRB2H (int R, int G, int B) {

        float H,S,V;

        int max = Math.max(R, Math.max(G, B));
        int min = Math.min(R, Math.min(G, B));
        int Delta = max - min;

        if (max == 0) {
            S = (float) 0.0;
        } else {
            S = (float) Delta/max;
        }

        if (max == R) {
            H = 60*(G-B)/Delta;
        } else if (max == G) {
            H = 120 + 60*(B-R)/Delta;
        } else  {
            H = 240 + 60*(R-G)/Delta;
        }

        if (H < 0.0) {
            H = 360 + H;
        } else if(H > 360.0) {
            H -= 360;
        }

        return H;
    }
}
